#include <iostream>
#include <unistd.h> 
#include <stdlib.h> 
#include <time.h>   
#include "RingQueue.hpp"

class Task
{
public:
    Task(int num1=1, int num2=2)
    :_num1(num1)
    ,_num2(num2)
    {}
    int Add()
    {
        return _num1+_num2;
    }
    int GetNum1()
    {
        return _num1;
    }
    int GetNum2()
    {
        return _num2;
    }
private:
    int _num1;
    int _num2;
};
//生产线程，生产数据和任务向阻塞队列中写
void* ProductRun(void* rags)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(rags); 
    while(true)
    {
        int num1 = rand()%10+1;//随机数范围在1~10之间
        usleep(1000);//休眠原因是使得两次生成的随机数不一样
        int num2 = rand()%10+1;
        Task task(num1, num2);
        rq->Enqueue(task);
        sleep(2);
    }

    return nullptr;
} 
//消费线程，读取数据执行任务
void* ConsumeRun(void* rags)
{
    RingQueue<Task>* rq = static_cast<RingQueue<Task>*>(rags); 
    Task task(1,2);
    while(true)
    {
        int num = 0;
        rq->Pop(task);
        std::cout << task.GetNum1() << " + " << task.GetNum2() << " = " << task.Add() <<std::endl;
    }

    return nullptr;
}
int main()
{
    srand(time(NULL));
    RingQueue<Task> rq(5);
    std::vector<pthread_t> threads;
    for(int i=0; i<5; ++i)
    {
        pthread_t PthreadId;
        pthread_create(&PthreadId, nullptr, ProductRun, (void*)&rq);
        threads.push_back(PthreadId);
    }
    for(int i=0; i<4; ++i)
    {
        pthread_t CThreadId;
        pthread_create(&CThreadId, nullptr, ConsumeRun, (void*)&rq);
        threads.push_back(CThreadId);
    }
    for(auto tmp:threads)
    {
        pthread_join(tmp, nullptr);
    }

    return 0;
}
